package com.leslie.hhcommunity.controller;

import com.leslie.hhcommunity.entity.DiscussPost;
import com.leslie.hhcommunity.entity.Page;
import com.leslie.hhcommunity.service.ElasticSearchService;
import com.leslie.hhcommunity.service.LikeService;
import com.leslie.hhcommunity.service.UserService;
import com.leslie.hhcommunity.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @PackageName:com.leslie.hhcommunity.controller
 * @ClassnName:SearchController
 * @Description:
 * @Date 2022/1/10  15:31
 */
@Controller
public class SearchController implements CommunityConstant {

	@Autowired
	ElasticSearchService elasticSearchService;
	@Autowired
	UserService userService;
	@Autowired
	LikeService likeService;

	@RequestMapping("/search")
	public String search(String keyWord, Page page, Model model){
		//搜索帖子
		org.springframework.data.domain.Page<DiscussPost> searchResult =
				elasticSearchService.searchDiscussPost(keyWord, page.getCurrent() - 1, page.getLimit());

		//聚合数据
		List<Map<String, Object>> discussPosts = new ArrayList<>();
		if (searchResult != null){
			for (DiscussPost post : searchResult) {
				Map<String, Object> map = new HashMap<>();
				//帖子
				map.put("post", post);
				//作者
				map.put("user", userService.findUserById(post.getUserId()));
				//点赞数量
				map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId()));
				discussPosts.add(map);
			}
		}
		model.addAttribute("discussPosts", discussPosts);
		model.addAttribute("keyWord", keyWord);
		// 分页信息
		page.setPath("/search?keyWord=" + keyWord);
		page.setRows(searchResult == null ? 0 : (int) searchResult.getTotalElements());
		return "site/search";
	}
}
